package com.mindmax.wordmemory.controller;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletResponse;

import com.mindmax.wordmemory.domain.FileStoreInfo;
import com.mindmax.wordmemory.domain.GenVoiceVO;
import com.mindmax.wordmemory.domain.InfoVocabulary;
import com.mindmax.wordmemory.mapper.FileStoreInfoMapper;
import com.mindmax.wordmemory.service.IInfoVocabularyService;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.StringUtils;
import org.apache.commons.collections4.MapUtils;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;


/**
 * 单词详情Controller
 *
 * @author cab
 * @date 2024-04-24
 */
@RestController
@RequestMapping("/word-memory/vocabulary-info")
@DataSource(value = DataSourceType.WORD_MEMORY)
public class InfoVocabularyController extends BaseController
{
    @Autowired
    private IInfoVocabularyService infoVocabularyService;
    @Autowired
    private FileStoreInfoMapper    fileStoreInfoMapper;



    @PutMapping("audio")
    public AjaxResult genVoice(@RequestBody GenVoiceVO genVoice)
    {
        String ids = genVoice.getIds();
        if (StringUtils.isEmpty(ids)) {
            return success();
        }
        Map<@Nullable Long, @Nullable String> m = infoVocabularyService.genVoice(ids);
        if (MapUtils.isNotEmpty(m)) {
            m.forEach((k, v) -> {
                FileStoreInfo fileStoreInfo = new FileStoreInfo();
                fileStoreInfo.setCreateTime(new Date());
                fileStoreInfo.setBucketName("mindmax-admin-files");
                fileStoreInfo.setFileOriginName(m.get(k));
                fileStoreInfo.setOssPath(m.get(k));
                fileStoreInfo.setSuffix("mp3");
                fileStoreInfoMapper.insert(fileStoreInfo);
                infoVocabularyService.updateInfoVocabularyStoreId(fileStoreInfo.getId(), k);
                logger.info("生成单词语音成功, infoID = {}, storeId = {}", k, fileStoreInfo.getId());
            });
        }
        return success();
    }

    @GetMapping("audio")
    public AjaxResult getAudio(@RequestParam(required =true) Long id)
    {
        var storeId = infoVocabularyService.selectInfoVocabularyById(id).getSentenceStoreId();
        FileStoreInfo fileStoreInfo = fileStoreInfoMapper.selectById(Long.valueOf(storeId));
        String ossPath = fileStoreInfo.getOssPath();
        long expireTime = LocalDateTime.now().plus(30, ChronoUnit.DAYS).atZone(ZoneOffset.ofHours(8)).toInstant().toEpochMilli();
        try {
            String encryptSignature = AESUtil.encrypt(String.format("%s:%d", storeId, expireTime), "W+u6PSQzjraRZE5G/h9Qpg==");
            String encryptSignatureEncoded = URLEncoder.encode(encryptSignature, StandardCharsets.UTF_8);
            return success(new HashMap<String, Object>() {{
                put("url", StringUtils.isEmpty(ossPath) ? "http://39.105.12.37/word-memory/download/"+fileStoreInfo.getId()+"?signature=" + encryptSignatureEncoded : ossPath);
            }});
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
    /**
     * 查询单词详情列表
     */
    //@PreAuthorize("@ss.hasPermi('system:vocabulary:list')")
    @GetMapping("/list")
    public TableDataInfo list(InfoVocabulary infoVocabulary) {

        startPage();
        List<InfoVocabulary> list = infoVocabularyService.selectInfoVocabularyList(infoVocabulary);
        return getDataTable(list);
    }

    /**
     * 导出单词详情列表
     */
    //@PreAuthorize("@ss.hasPermi('system:vocabulary:export')")
    @Log(title = "单词详情", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, InfoVocabulary infoVocabulary)
    {
        List<InfoVocabulary> list = infoVocabularyService.selectInfoVocabularyList(infoVocabulary);
        ExcelUtil<InfoVocabulary> util = new ExcelUtil<InfoVocabulary>(InfoVocabulary.class);
        util.exportExcel(response, list, "单词详情数据");
    }

    /**
     * 获取单词详情详细信息
     */
    //@PreAuthorize("@ss.hasPermi('system:vocabulary:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(infoVocabularyService.selectInfoVocabularyById(id));
    }

    /**
     * 新增单词详情
     */
    //@PreAuthorize("@ss.hasPermi('system:vocabulary:add')")
    @Log(title = "单词详情", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody InfoVocabulary infoVocabulary)
    {
        return toAjax(infoVocabularyService.insertInfoVocabulary(infoVocabulary));
    }

    /**
     * 修改单词详情
     */
    //@PreAuthorize("@ss.hasPermi('system:vocabulary:edit')")
    @Log(title = "单词详情", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody InfoVocabulary infoVocabulary)
    {
        return toAjax(infoVocabularyService.updateInfoVocabulary(infoVocabulary));
    }

    /**
     * 删除单词详情
     */
    //@PreAuthorize("@ss.hasPermi('system:vocabulary:remove')")
    @Log(title = "单词详情", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(infoVocabularyService.deleteInfoVocabularyByIds(ids));
    }
}
